﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using SharpDiary.Core.ORMapping;
using SharpDiary.Core.Utility;
using SharpDiary.Core.Data;
using SharpDiary.Core.Controls;

namespace SharpDiary.Diary
{
    public partial class DiaryInfoControlList : ListControlBase
    {
        private readonly int PAGE_SIZE = 10;
        private int _summaryTextMaxLength = 20;
        private long _rowCountPerpage = 10;

        public DiaryInfoControlList()
        {
            InitializeComponent();

            DoubleBuffered = true;
            ResizeRedraw = true;
        }

        /// <summary>
        /// 获取总页数。
        /// </summary>
        /// <returns></returns>
        protected override long GetPageCount()
        {
            return Utils.CalculatePageCount(DiaryInfo.GetRowCount<DiaryInfo>(), _rowCountPerpage);
        }

        /// <summary>
        /// 显示所有日记的第一页。
        /// </summary>
        public override void ShowItems()
        {
            base.ShowItems();

            _summaryTextMaxLength = int.Parse(UserSettings.GetInstance().GetSettingValue("SummaryTextMaxLength", "20"));
            if (LinkedPageButtonGroup != null) { LinkedPageButtonGroup.PageCount = GetPageCount(); }

            //显示第一页。
            StringBuilder sql = new StringBuilder();
            sql.AppendLine("select * from Diary");
            sql.AppendLine("order by CreatedDatetime desc");

            List<DiaryInfo> diaries = DbObjectMappingHelper.QueryObjectList<DiaryInfo>(sql.ToString(), _rowCountPerpage, 1);
            ShowDiaryItems(diaries);
        }

        /// <summary>
        /// 显示日记项。
        /// </summary>
        /// <param name="diaries"></param>
        private void ShowDiaryItems(List<DiaryInfo> diaries)
        {
            Clear();

            //要倒着插，才会得到想要正着显示的结果。
            for (int i = diaries.Count - 1; i >= 0; i--)
            {
                DiaryInfo diary = diaries[i];
                diary = DiaryInfo.DecryptDiaryInfo(diary);
                DiaryInfoListItemControl control = new DiaryInfoListItemControl();
                control.SummaryTextMaxLength = _summaryTextMaxLength;
                control.Diary = diary;
                control.PopupMenu = contextMenu;

                AddItem(control);
            }
        }

        /// <summary>
        /// 搜索。
        /// </summary>
        /// <param name="keywords">关键字</param>
        /// <returns>匹配的结果个数</returns>
        public override int Search(string keywords)
        {
            if (string.IsNullOrEmpty(keywords)) { return 0; }

            int matchedCount = 0;
            long totalPageCount = GetPageCount(); //总页数
            long pageNumber = 1;
            string title = string.Empty;          //日记标题
            string content = string.Empty;        //日记内容
            string id = string.Empty;             //日记编码

            //显示第一页。
            StringBuilder sql = new StringBuilder();
            sql.AppendLine("select * from Diary");
            sql.AppendLine("order by CreatedDatetime desc");

            DataAccessService das = Utils.GetDataAccessServiceInstance();

            DiaryInfo.ResetSearchFlag(0);  //开始新的搜索前要重置搜索标识。

            //以页为单位读取日记信息，然后从日记信息中搜索匹配的关键字
            for (pageNumber = 1; pageNumber <= totalPageCount; pageNumber++)
            {
                DataTable table = das.GetDataTable(sql.ToString(), _rowCountPerpage, pageNumber, CommandType.Text);
                foreach (DataRow row in table.Rows)
                {
                    id = row["Id"].ToString();
                    title = UserSettings.ShellInstance.CryptionService.Decrypt(row["Title"].ToString());
                    content = UserSettings.ShellInstance.CryptionService.Decrypt(row["Content"].ToString());

                    if (title.IndexOf(keywords, StringComparison.CurrentCultureIgnoreCase) != -1
                        || content.IndexOf(keywords, StringComparison.CurrentCultureIgnoreCase) != -1)
                    {
                        matchedCount++;
                        DiaryInfo.UpdateSearchFlag(id, 1); //标识此日记中有匹配的关键字
                    }
                }
            }

            //显示所有标识为匹配关键字的日记。(SearchFlag = 1)
            sql = new StringBuilder();
            sql.AppendLine("select * from Diary");
            sql.AppendLine("where SearchFlag = 1");
            sql.AppendLine("order by CreatedDatetime desc");

            List<DiaryInfo> diaries = DbObjectMappingHelper.QueryObjectList<DiaryInfo>(sql.ToString(), _rowCountPerpage, 1);
            ShowDiaryItems(diaries);

            _isSearchResult = true;
            if (LinkedPageButtonGroup != null)
            {
                LinkedPageButtonGroup.PageCount = Utils.CalculatePageCount(matchedCount, _rowCountPerpage); //计算搜索结果的页数
            }

            return matchedCount;
        }

        /// <summary>
        /// 当前页码发生改变后执行此方法。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected override void LinkedPageButtonGroup_PageNumberChanged(object sender, PageNumberChangedEventArgs e)
        {
            base.LinkedPageButtonGroup_PageNumberChanged(sender, e);

            Clear();

            StringBuilder sql = new StringBuilder();
            sql.AppendLine("select * from Diary");
            if (IsSearchResult) //显示搜索结果
            {
                sql.AppendLine("where SearchFlag = 1");
            }
            sql.AppendLine("order by CreatedDatetime desc");

            List<DiaryInfo> diaries = DbObjectMappingHelper.QueryObjectList<DiaryInfo>(sql.ToString(), _rowCountPerpage, e.CurrentPageNumber);
            ShowDiaryItems(diaries);
        }

        private void contextMenu_Popup(object sender, EventArgs e)
        {
            DiaryInfoListItemControl item = this.SelectedItem as DiaryInfoListItemControl;
            if (item == null || item.Diary == null || item.NeedEnterPassword)
            {
                foreach (MenuItem menuItem in item.PopupMenu.MenuItems)
                {
                    menuItem.Visible = false;
                }
            }
            else
            {
                foreach (MenuItem menuItem in item.PopupMenu.MenuItems)
                {
                    menuItem.Visible = true;
                }

                miModifyPrivatePassword.Enabled = (item.Diary != null &&
                    !string.IsNullOrEmpty(item.Diary.PrivatePasswordMD5));
                miRemovePrivatePassword.Enabled = miModifyPrivatePassword.Enabled;
                miSetPrivatePassword.Enabled = !miModifyPrivatePassword.Enabled;
            }
        }

        private void miSetPrivatePassword_Click(object sender, EventArgs e)
        {
            DiaryInfoListItemControl item = this.SelectedItem as DiaryInfoListItemControl;
            if (item != null && item.Diary != null && !item.NeedEnterPassword)
            {
                UserSettings.ShellInstance.ExecuteAction("SharpDiary.Diary", "48d65655-85b9-4503-a0a6-3adea7fe6b71", item.Diary, item);
            }

        }

        private void miModifyPrivatePassword_Click(object sender, EventArgs e)
        {
            DiaryInfoListItemControl item = this.SelectedItem as DiaryInfoListItemControl;
            if (item != null && item.Diary != null && !item.NeedEnterPassword)
            {
                UserSettings.ShellInstance.ExecuteAction("SharpDiary.Diary", "48d65655-85b9-4503-a0a6-3adea7fe6b71", item.Diary, item);
            }
        }

        /// <summary>
        /// 删除日记独立访问密码。
        /// </summary>
        /// <param name="diary"></param>
        /// <returns></returns>
        private bool RemoveDiaryPrivatePassword(DiaryInfo diary)
        {
            if (diary == null) { return false; }

            diary.PrivatePasswordMD5 = string.Empty;
            return DiaryInfo.Update<DiaryInfo>(diary);
        }

        private void miRemovePrivatePassword_Click(object sender, EventArgs e)
        {
            DiaryInfoListItemControl item = this.SelectedItem as DiaryInfoListItemControl;
            if (item != null && item.Diary != null)
            {
                if (MessageBoxHelper.ShowConfirmation("您确定要删除此日记的独立访问密码吗？") == DialogResult.Yes)
                {
                    if (!RemoveDiaryPrivatePassword(item.Diary))
                    {
                        MessageBoxHelper.ShowAlert("删除独立访问密码失败。");
                    }
                }
            }
        }
    }
}
